<?php
namespace app\api\model;

//use think\Cache;
//use app\common\library\helper;


class Cardnfc extends Base
{
    //NFC卡

    /**
     * 商户登录
     * @param string $uname 账号
     * @param string $passwd 密码
     */
    public function dologin($uname, $passwd)
    {
        $uOne = $this->dbConn($this->dbStoreUser)
            ->where([
                'is_delete' => 0,
                'user_name' => $uname,
            ])
            ->find();
        if (!$uOne) {
            return $this->toback(-2, '没有记录');
        }
        if ($uOne['password'] != shopdod_hash($passwd)) {
            return $this->toback(-2, '密码错误');
        }
        $token = md5($uOne['store_user_id'].'-'.time());
        $this->dbConn($this->dbStoreUser)
            ->where(['store_user_id' => $uOne['store_user_id']])
            ->update(['login_token' => $token]);
        $arys = [
            'token' => $token,
            'uname' => $uname,
        ];
        return $this->toback(0, '', $arys);
    }

    /**
     * 添加卡
     * @param array $pas
     */
    public function cardSet($pas)
    {
        $storeOne = (array) $this->dbConn($this->dbStoreUser)
            ->where([
                'is_delete' => 0,
                'login_token' => $pas['token'],
            ])
            ->find();
        if (!$storeOne) {
            return $this->toback(-2, '商家不存在');
        }
        //头像处理
        $uheadArys = [];
        for ($i = 1; $i < 23; $i ++) {
            $uheadArys[] = 'uploads/uhead/'.$i.'.png';
        }
        $headkey = array_rand($uheadArys);
        $uhead = $uheadArys[$headkey];
        //看看用户有没有
        $uOne = $this->dbConn($this->dbUser)
            ->where([
                'is_delete' => 0,
                'phone' => $pas['phone'],
            ])
            ->find();
        if (!$uOne) {
            $uid = $this->dbConn($this->dbUser)->insertGetId([
                'phone' => $pas['phone'],
                'nickName' => $pas['realname'],
                'balance' => $pas['amount'],
                'avatarUrl' => $uhead,
                'create_time' => time(),
                'update_time' => time(),
            ]);
        } else {
            if (!$uOne['avatarUrl']) {
                $this->dbConn($this->dbUser)->where('user_id', $uOne['user_id'])
                    ->update(['avatarUrl' => $uhead]);
            }
            $uid = $uOne['user_id'];
        }
        $res = $this->dbConn($this->dbStoreCard)
            ->where([
                'del' => 0,
                'serial' => $pas['serial'],
            ])
            ->find();
        if ($res && $res['uid']) {
            return $this->toback(-2, '此卡已被使用');
        }
        $riqi = date('Y-m-d H:i:s', time());
        if (!$pas['serial']) {
            $pas['serial'] = date('YmdHis', time()) . rand(100, 999);
        }
        //判断卡是否存在
        if (!$res) {
            $card_token = md5('C' . date('YmdHis', time()) . rand(100, 999));
            $card_id = $this->dbConn($this->dbStoreCard)->insertGetId([
                'card_token' => $card_token,
                'serial' => $pas['serial'],
                'cardno' => $pas['cardno'],
                'store_id' => $storeOne['store_user_id'],
                'uid' => $uid,
                'realname' => $pas['realname'],
                'phone' => $pas['phone'],
                'amount' => $pas['amount'] * 100,
                'addtime' => $riqi, 'uptime' => $riqi,
            ]);
        } else {
            if ($res['uid']) {
                return $this->toback(-2, '此ID卡已在使用中');
            }
            //填充数据
            $this->dbConn($this->dbStoreCard)
                ->where('id', $res['id'])
                ->update([
                    'serial' => $pas['serial'],
                    'cardno' => $pas['cardno'],
                    'store_id' => $storeOne['store_user_id'],
                    'uid' => $uid,
                    'realname' => $pas['realname'],
                    'phone' => $pas['phone'],
                    'amount' => $pas['amount'] * 100,
                    'uptime' => $riqi,
                ]);
            $card_id = $res['id'];
        }
        //添加卡记录
        $this->dbConn($this->dbCostList)->insertGetId([
            'card_id' => $card_id,
            'store_id' => $storeOne['store_user_id'],
            'uid' => $uid,
            'amount' => $pas['amount'] * 100,
            'type' => 1,
            'oper' => 1,
            'addtime' => $riqi,
        ]);
        return $this->toback();
    }

    /**
     * 卡充值
     * @param string $serial 卡ID
     * @param int $amount 充值额度
     */
    public function recharge($serial, $amount)
    {
        $res = $this->dbConn($this->dbStoreCard)
            ->where([
                'del' => 0,
                'serial' => $serial,
            ])
            ->find();
        if (!$res) {
            return $this->toback(-2, '卡不存在');
        }
        //设置余额
        $this->dbConn($this->dbStoreCard)->where('id', $res['id'])
            ->update(['amount' => $res['amount'] + $amount, 'uptime' => $this->toDate()]);
        //设置充值记录
        $this->dbConn($this->dbCostList)->insertGetId([
            'card_id' => $res['id'], 'store_id' => $res['store_id'], 'uid' => $res['uid'],
            'type' => 1, 'oper' => 1, 'amount' => $amount, 'addtime' => $this->toDate(),
        ]);
        return $this->toback();
    }

    /**
     * 卡列表
     */
    public function cardList($token, $status)
    {
        $storeOne = $this->dbConn($this->dbStoreUser)
            ->where([
                'is_delete' => 0,
                'login_token' => $token,
            ])
            ->find();
        if (!$storeOne) {
            return $this->toback(-2, '商家不存在');
        }
        $store_id = $storeOne['store_user_id'];
        if ($status == 1) {
            $res = $this->dbConn($this->dbStoreCard)
//                ->where([
//                    ['store_id', '=', $storeOne['store_user_id']],
//                    ['uid', '>', 0]
//                ])
                ->where('store_id', '=', $store_id)
                ->where('uid', '>', 0)
                ->select()->toArray();
        } else if ($status == 2) {
            $res = $this->dbConn($this->dbStoreCard)
                ->where([
                    'store_id' => $storeOne['store_user_id'],
                    'uid' => 0,
                ])
                ->select()->toArray();
        } else {
            $res = $this->dbConn($this->dbStoreCard)
                ->where(['store_id' => $storeOne['store_user_id']])
                ->select()->toArray();
        }
        if (!count($res)) {
            return $this->toback();
        }
        $arys = [];
        foreach ($res as $v) {
            $uOne = $this->dbConn($this->dbUser)
                ->where(['user_id' => $v['uid']])
                ->find();
            $iswx = 0;
            if ($uOne && $uOne['open_id']) {
                $iswx = 1;
            }
            $arys[] = [
                'cardno' => $v['cardno'],
                'iswx' => $iswx ? '已绑定' : '未绑定',
                'time' => date('Y/m/d H:i:s', strtotime($v['addtime'])),
                'status' => $v['uid'] ? '使用中' : '未使用',
                'balance' => round(($v['amount'] / 100), 2)
            ];
        }
        return $this->toback(0, '', $arys, count($arys));
    }

    /**
     * 卡详情
     */
    public function cardOne($serial)
    {
        $res = $this->dbConn($this->dbStoreCard)
            ->where(['serial' => $serial])
            ->find();
        if (!$res) {
            return $this->toback(-2, '没有记录');
        }
        if (!$res['uid']) {
            return $this->toback(-2, '这是空卡');
        }
        $res['amount'] = round(($res['amount'] / 100), 2);
        return $this->toback(0, '', $res);
    }

    /**
     * 退卡
     */
    public function cardRefund($serial)
    {
        $res = $this->dbConn($this->dbStoreCard)
            ->where([
                'serial' => $serial,
            ])
            ->find();
        if (!$res) {
            return $this->toback(-2, '没有记录');
        }
        if (!$res['uid']) {
            return $this->toback(-2, '已退卡');
        }
        $this->dbConn($this->dbStoreCard)
            ->where(['serial' => $serial])
            ->update([
                'store_id' => 0,
                'uid' => 0,
                'realname' => '',
                'phone' => '',
                'amount' => 0,
                'refundtime' => date('Y-m-d H:i:s', time()),
            ]);
        $this->dbConn($this->dbCostList)
            ->where(['card_id' => $res['id'], 'is_refund' => 0])
            ->update([
                'is_refund' => 1,
                'refundtime' => date('Y-m-d H:i:s', time()),
            ]);
        return $this->toback();
    }

    /**
     * 消费列表
     */
    public function costList($serial, $type)
    {
        $cardOne = $this->dbConn($this->dbStoreCard)
            ->where([
                'del' => 0,
                'serial' => $serial,
            ])
            ->find();
        if (!$cardOne) {
            return $this->toback(-2, '卡不存在');
        }
        if ($type == 2) { //消费
            $res = $this->dbConn($this->dbCostList)
                ->where('del', 0)
                ->where('card_id', $cardOne['id'])
                ->where('type', $type)
                ->select()->toArray();
        } else if ($type == 1) { //充值
            $res = $this->dbConn($this->dbCostList)
                ->where('del', 0)
                ->where('card_id', $cardOne['id'])
                ->whereIn('type', [1, 2])
                ->select()->toArray();
        } else {
            $res = $this->dbConn($this->dbCostList)
                ->where('del', 0)
                ->where('card_id', $cardOne['id'])
                ->select()->toArray();
        }
        if (!count($res)) {
            return $this->toback(-2, '没有记录');
        }
        $types = [ 1 => '线下充值', '微信充值', '消费',];
        $arys = [];
        foreach ($res as $v) {
            $tname = array_key_exists($v['type'], $types) ? $types[$v['type']] : '';
            $operName = $v['oper']==1 ? '+' : '-';
            $arys[] = [
                'type_name' => $tname,
                'time' => date('Y/m/d H:i:s', strtotime($v['addtime'])),
                'cost' => $operName . round(($v['amount'] / 100), 2) . '元'
            ];
        }
        return $this->toback(0, '', $arys);
    }
}